import {createRouter, createWebHistory} from "vue-router";
import {constRoutes} from "./constRoutes.ts";
import useUserStore from "@/store/UserStore.ts";
import pinia from "@/store";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css';

const userStore = useUserStore(pinia);
const router = createRouter({
    history: createWebHistory(),
    routes: constRoutes,
    // 路由滚轮定制。切换页面后滚轮在顶部
    scrollBehavior(): { top: number } {
        return {
            top: 0,
        };
    },
});
// 前置守卫
router.beforeEach(async (to, from, next) => {
    let s = localStorage.getItem("user") ;
    const user = s ? JSON.parse(s) : null;
    if(user?.token) {
        // 已登录
        if(to.path == "/login")
            next("/");
        else {
            if (user.username !== "") {
                next();
            } else {
                try {
                    await userStore.getUserInfo();
                    next({...to}); // 保证异步路由加载完毕
                } catch (e) {
                    ElMessage({
                        type: "error",
                        message: (e as Error).message
                    });
                    next({path:"/login",query:{redirect:to.path}});
                }
            }
        }
    } else {
        // 未登录
        if (to.path == "/login")
            next();
        else
            next({path:"/login",query:{redirect:to.path}});
    }

});
// 后置守卫

export default router;
